/* 
 * Copyright (C) 2008 OpenIntents.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.berry.MedCheck.export;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import com.berry.MedCheck.DataActivity;
import com.berry.MedCheck.R;
import com.berry.MedCheck.Utils;
import com.berry.MedCheck.db.UserDB;


import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class ExportCsvThread extends Thread{

	Context mContext;
	Cursor mCursor;
	Writer mWriter;
	Handler mHandler;

	public ExportCsvThread(Context context, Cursor cursor, Writer writer, Handler handler) {
		mContext = context;
		mCursor = cursor;
		mWriter = writer;
		mHandler = handler;
	}

	@Override
	public void run() {
		CSVWriter csvwriter = new CSVWriter(mWriter);
		if (mCursor != null) {
			mCursor.moveToFirst();
			int iSpo2 = mCursor.getColumnIndex(UserDB.DBColumns.SPO2);
			int iPr = mCursor.getColumnIndex(UserDB.DBColumns.PR);
			int iPi = mCursor.getColumnIndex(UserDB.DBColumns.PI);
			int iDate = mCursor.getColumnIndex(UserDB.DBColumns.DATE);
			csvwriter.write(mContext.getString(R.string.csv_title_date));
			csvwriter.write(mContext.getString(R.string.csv_title_spo2));
			csvwriter.write(mContext.getString(R.string.csv_title_pr));
			csvwriter.write(mContext.getString(R.string.csv_title_pi));
			csvwriter.writeNewline();
			while (mCursor.moveToNext()) {
				int dataSpo2 = mCursor.getInt(iSpo2);
				int dataPR = mCursor.getInt(iPr);
				float dataPI = mCursor.getFloat(iPi);
				long dataDate = mCursor.getLong(iDate);
				String time = Utils.getFullDate(dataDate);
				csvwriter.write(time);
				csvwriter.write(Integer.toString(dataSpo2));
				csvwriter.write(Integer.toString(dataPR));
				csvwriter.write(Double.toString(dataPI));
				csvwriter.writeNewline();
			}
		}
		try {
			csvwriter.close();
			mHandler.obtainMessage(Utils.HANDLE_MSG_EXPORT_DONE, 0, -1).sendToTarget();
		} catch (IOException e) {
			e.printStackTrace();
			mHandler.obtainMessage(Utils.HANDLE_MSG_EXPORT_FAIL, 0, -1).sendToTarget();

		}


	}



}
